package Java_Lab.Multithreading.CycledThreads;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class CyclicThreads{
	
	private final List<Worker> workers = new LinkedList<Worker>();
	
	private Iterator<Worker> iterator;
	
	/**
	 * Worker that must be run. Each evoked thread checks whether it equals
	 * this worker, if so, the thread runs, else the thread waits.
	 */
	volatile Worker currentWorker;
	
	public void addWorker(Worker worker){
		workers.add(worker);
	}
	
	public void removeWorker(int index){
		workers.remove(index);
	}
	
	public void start(){
		defineNext();
		for(Worker worker : workers){
			Thread newThread = new Thread(worker);
			newThread.start();
		}
	}
	
	void defineNext(){
		if(iterator == null || !iterator.hasNext()){
			iterator = workers.iterator();
		}
		currentWorker = iterator.next();
	}
	
	public static void main(String[] str){
		CyclicThreads cyclicThreads = new CyclicThreads();
		for(int i = 0; i < 4; i++)
			cyclicThreads.addWorker(new Worker("Worker " + i, cyclicThreads));
		cyclicThreads.start();
	}
}
